package com.sgb.kjwl.viewmodel.home;

import android.text.TextUtils;

import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.model.entity.BiddingEntity;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.sgb.jicai.entity.FactoryCentralizedListEntity;
import com.sgb.kjwl.model.entity.LeaseSearchResultEntity;
import com.sgb.kjwl.model.entity.LeaseSearchResultTypeEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.TenderListEntity;
import com.sgb.jicai.entity.JiCaiHomeListRequestBean;
import com.sgb.kjwl.model.entity.pick.PickSearchTender;
import com.sgb.kjwl.model.entity.pick.PreNoticeItemEntity;
import com.sgb.jicai.entity.FactoryCentralizedItemEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.model.response.ListResponse2;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.fragment.home.SearchNewChildFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SearchNewChildFragModel extends BaseViewModel {

    private SearchNewChildFragment fragment;
    private HomeRepertory repertory;
    public JiCaiHomeListRequestBean jiCaiHomeListRequestBean;

    private Map map;
    private int limit = 10;

    public SearchNewChildFragModel(SearchNewChildFragment fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    public void getFilterTypeData() {
        APIManager.getInstance().getPickAPI().biddingTypeList().enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setPickFilterType(data.getData());
                }
            }
        });
    }


    public void getPickFilterType() {
        APIManager.getInstance().getPickAPI().getProjectType().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setPickFilterType(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                t.printStackTrace();
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getPickTenderList(String type, String keyword, int page, boolean isLoadMore) {
        map = new HashMap();
        map.put("page", page);
        map.put("limit", limit);
        if (TextUtils.isEmpty(type) || TextUtils.equals("0", type)) {
            map.put("type", "");
        } else {
            map.put("type", type);
        }
        map.put("keyword", keyword);
        map.put("comName", "");
        map.put("total", "");
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "加载中", 0, true, null, false);
        APIManager.getInstance().getPickAPI().findTenderPage(map).enqueue(new Callback<BaseEntity<PickSearchTender<List<TenderListEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<PickSearchTender<List<TenderListEntity>>>> call, Response<BaseEntity<PickSearchTender<List<TenderListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null) {
                        if (response.body().getData().isLastPage()) {
                            fragment.showPickTenderList(response.body().getData().getList(), isLoadMore, true);
                        } else {
                            fragment.showPickTenderList(response.body().getData().getList(), isLoadMore, false);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PickSearchTender<List<TenderListEntity>>>> call, Throwable t) {
                t.printStackTrace();
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getPickBigList(String type, String keyword, int page, boolean isLoadMore) {
        map = new HashMap();
        map.put("page", page);
        map.put("limit", limit);
        if (!TextUtils.isEmpty(type) && !"0".equals(type))
            map.put("type", type);
        map.put("keyword", keyword);
        map.put("comName", "");
        map.put("total", "");
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "加载中", 0, true, null, false);
        APIManager.getInstance().getPickAPI().findBidPage(map).enqueue(new Callback<BaseEntity<PickSearchTender<List<BiddingEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<PickSearchTender<List<BiddingEntity>>>> call, Response<BaseEntity<PickSearchTender<List<BiddingEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData() != null) {
                        if (response.body().getData().isLastPage()) {
                            fragment.showPickBigList(response.body().getData().getList(), isLoadMore, true);
                        } else {
                            fragment.showPickBigList(response.body().getData().getList(), isLoadMore, false);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PickSearchTender<List<BiddingEntity>>>> call, Throwable t) {
                t.printStackTrace();
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getPickBigNoticeList(String type, String keyword, int page, boolean isLoadMore) {
        map = new HashMap();
        map.put("page", page);
        map.put("limit", limit);
        map.put("type", type);
        map.put("keyword", keyword);
        map.put("comName", "");
        map.put("total", "");
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "加载中", 0, true, null, false);
        APIManager.getInstance().getPickAPI().findBidNoticePage(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<PreNoticeItemEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<PreNoticeItemEntity>>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (data.getData() != null) {
                        if (data.getData().isLastPage()) {
                            fragment.showPickBigNoticeList(data.getData().getList(), isLoadMore, true);
                        } else {
                            fragment.showPickBigNoticeList(data.getData().getList(), isLoadMore, false);
                        }
                    }
                }
            }
        });
    }

    public void groupBuyClassList() {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "加载中...", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getCentralizedMiningAPI().groupBuyClassList().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setCollectFilter1Type(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }

        });
    }

    public void getTenderGoodsCategoryAllList(String no) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "加载中...", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getCentralizedMiningAPI().getSecondCategory(no, "1").enqueue(new Callback<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CommonPopEntity>>> call, Response<BaseEntity<List<CommonPopEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setCollectFilter2Type(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CommonPopEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 需方发起列表
     */
    public void getJiCaiList(String searchKey, int page, boolean isLoadMore, String groupBuyClass) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "加载中...", 0, true, null).setCanceledOnTouchOutside(false);
        jiCaiHomeListRequestBean = new JiCaiHomeListRequestBean();
        jiCaiHomeListRequestBean.setCurrent(page);
        jiCaiHomeListRequestBean.setLimit(limit);
        jiCaiHomeListRequestBean.setGroupBuyMode("1");
        jiCaiHomeListRequestBean.setSearchKey(searchKey);
        if ("0".equals(groupBuyClass)) {
            groupBuyClass = "";
        }
        jiCaiHomeListRequestBean.setGroupbuyClass(groupBuyClass);
        APIManager.getInstance().getCentralizedMiningAPI().getJiCaiLists(jiCaiHomeListRequestBean).enqueue(new ICallBack<BaseEntity<ListResponse<List<CentralizedMiningEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<CentralizedMiningEntity>>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (data.getData().isLastPage()) {
                        fragment.showCollectFilter1List(data.getData().getList(), isLoadMore, true);
                    } else {
                        fragment.showCollectFilter1List(data.getData().getList(), isLoadMore, false);
                    }
                }
            }
        });
    }

    /**
     * 获取供方发起列表
     */
    public void getFactoryCentralizedList(String searchKey, int page, boolean isLoadMore, String firstType) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "加载中...", 0, true, null).setCanceledOnTouchOutside(false);
        jiCaiHomeListRequestBean = new JiCaiHomeListRequestBean();
        jiCaiHomeListRequestBean.setCurrent(page);
        jiCaiHomeListRequestBean.setLimit(limit);
        jiCaiHomeListRequestBean.setSearchKey(searchKey);
        if ("0".equals(firstType)) {
            firstType = "";
        }
        jiCaiHomeListRequestBean.setFirstType(firstType);
        APIManager.getInstance().getCentralizedMiningAPI().getFactoryCentralizedLists(jiCaiHomeListRequestBean).enqueue(new ICallBack<BaseEntity<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<FactoryCentralizedListEntity<FactoryCentralizedItemEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                boolean isLastPage = !(data.getData().getTotal() > data.getData().getCurrent());//判断是否是最后一页可能有误
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showCollectFilter2List(data.getData().getList(), isLoadMore, isLastPage);
                } else {
                    MToast.showToast(fragment.getContext(), data.getMsg());
                }
            }
        });
    }

    //租赁搜索的类目查询
    public void getLeaseType() {
        APIManager.getInstance().getLeaseAPI().getLeaseType()
                .enqueue(new Callback<BaseEntity<List<LeaseSearchResultTypeEntity>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<LeaseSearchResultTypeEntity>>> call, Response<BaseEntity<List<LeaseSearchResultTypeEntity>>> response) {
                        if (response.body() == null || response.body().getState() == null) {
                            return;
                        }
                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            fragment.setRentFilterType(response.body().getData());
                        }

                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<LeaseSearchResultTypeEntity>>> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    //租赁搜索
    public void getLeaseHomeSearch(String rentType, String keyword, String type, int page, boolean isLoadMore) {
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        map = new HashMap();
        map.put("current", page);
        map.put("sortWay", "1");
        map.put("limit", limit);
        map.put("keyword", keyword);
        map.put("rentType", rentType);
        map.put("firstCategoryNo", "");
        if ("0".equals(type)) {
            type = "";
        }
        map.put("type", type);
        map.put("longitude", "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE, ""))
                ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LONGITUDE, ""));
        map.put("latitude", "".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE, ""))
                ? repertory.getLatitude() : SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LATITUDE, ""));
        APIManager.getInstance().getLeaseAPI().getLeaseHomeSearchs(map)
                .enqueue(new Callback<BaseEntity<ListResponse2<List<LeaseSearchResultEntity>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<ListResponse2<List<LeaseSearchResultEntity>>>> call, Response<BaseEntity<ListResponse2<List<LeaseSearchResultEntity>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null || response.body().getState() == null) {
                            return;
                        }
                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            if (response.body().getData() != null) {
                                if (response.body().getData().getTotalPage() == response.body().getData().getCurrentPage()) {
                                    fragment.showRentList(response.body().getData().getList(), isLoadMore, true);
                                } else {
                                    fragment.showRentList(response.body().getData().getList(), isLoadMore, false);
                                }
                            }
                        }

                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ListResponse2<List<LeaseSearchResultEntity>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    /**
     * 出租详情
     */
    public void getH5Url(String id, String type) {
        String name = "";
        if ("1".equals(type)) {
            name = "mechanicsDetail";//机械
        } else if ("2".equals(type)) {
            name = "equipmentDetails";//设备
        } else if ("3".equals(type)) {
            name = "vehicleDetails";//车辆
        } else if ("4".equals(type)) {
            name = "propertyDetails";//房产
        } else if ("5".equals(type)) {
            name = "landDetails";//土地
        } else if ("6".equals(type)) {
            name = "factoryDetails";//工厂
        } else if ("7".equals(type)) {
            name = "farmDetail";//农机
        }

        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(name).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id + "&iosFlag=1";
//                    WebViewX5HostActivity.start(fragment.getActivity(), url);
                    WebViewX5HostActivity.start(fragment.getActivity(), url, id, "lease", type);
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 求租详情
     */
    public void getAskH5Url(String id, String type) {
        String urlName = "";
        if ("1".equals(type)) {//机械
            urlName = "mechanicsRentDetails";
        } else if ("2".equals(type)) {//设备
            urlName = "equipmentRentDetails";
        } else if ("3".equals(type)) {//车辆
            urlName = "vehicleRentDetails";
        } else if ("4".equals(type)) {//房产
            urlName = "houseRentDetails";
        } else if ("5".equals(type)) {//土地
            urlName = "landRentDetails";
        } else if ("6".equals(type)) {//工厂
            urlName = "factoryRentDetails";
        } else if ("7".equals(type)) {//农机
            urlName = "farmRentDetails";
        } else {
            return;
        }

        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(urlName).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id;
//                    WebViewX5HostActivity.start(fragment.getActivity(), url);
                    WebViewX5HostActivity.start(fragment.getActivity(), url,id,"asklease",type);
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 竞价详情
     */
    public void getUrlSetting(String id) {
        DialogHelper.showProgressDialog2(fragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        APIManager.getInstance().getPickAPI().getUrlSetting("competitivePurchase").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id;
                    String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                    String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                    url = url + "&lng=" + lng + "&lat=" + lat;
                    MLog.d("api", "H5跳转链接  " + url);
                    fragment.getUrl(url);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    /**
     * 需方,供方详情
     */
    public void getH5UrlCollect(String id, String tag) {
        DialogHelper.showProgressDialog(fragment.getActivity(), "加载中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(tag).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {

            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {//type 0 首页 1 我的集采 2 我的报价
                    SharedPreferenceUtil.init(fragment.getActivity());
                    String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.resourceAPPToken, "");
                    String url = null;
                    if ("collection".equals(tag)) {
                        url = data.getData().getUrl() + "?id=" + id + "&type=0" + "&token=" + token;
                    } else if ("Factory".equals(tag)) {
                        url = data.getData().getUrl() + "?id=" + id;
                    }
                    fragment.getUrl(url);
                } else {
                    MToast.showToast(fragment.getContext(), data.getMsg());
                }
            }
        });
    }

    public void getUrlSettingTender(String id) {
        DialogHelper.showProgressDialog2(fragment.getActivity(), null, "加载中", 0, true, null, false);
        APIManager.getInstance().getPickAPI().getUrlSetting("FrontDeskBidding").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id;
                    String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                    String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                    url = url + "&lng=" + lng + "&lat=" + lat;
                    MLog.d("api", "H5跳转链接  " + url);
                    fragment.getUrl(url, id);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }
}
